package com.sk.weichat.ui.mucfile;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.R;
import com.sk.weichat.ui.base.LazyFragment;
import com.sk.weichat.ui.mucfile.adapter.DividerAdapter;
import com.sk.weichat.ui.mucfile.adapter.EmptyAdapter;
import com.sk.weichat.ui.mucfile.adapter.FileAdapter;
import com.sk.weichat.ui.mucfile.adapter.TypeAdapter;
import com.sk.weichat.ui.mucfile.bean.FileBean;
import com.sk.weichat.util.MediaHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.sk.weichat.ui.mucfile.AddMucFileActivity2.Action_Click;

public class MediaFileFragment2 extends LazyFragment implements MediaHelper.OnQueryListener {
    SmartRefreshLayout refreshLayout;
    private DelegateAdapter delegateAdapter;
    private LinkedList<DelegateAdapter.Adapter> adapterList = new LinkedList<>();
    //记录展开的项
    Map<String, Boolean> expandMap = new HashMap<>();
    //记录选择的Item
    Map<String, Boolean> checkedMap = new HashMap<>();

    TypeAdapter wordAdapter;
    TypeAdapter pdfAdapter;
    TypeAdapter pptAdapter;
    TypeAdapter excelAdapter;
    FileAdapter wordfileAdapter;
    FileAdapter pdffileAdapter;
    FileAdapter pptfileAdapter;
    FileAdapter excelfileAdapter;


    List<FileBean> wordFiles = new ArrayList<>();
    List<FileBean> pdffiles = new ArrayList<>();
    List<FileBean> pptfiles = new ArrayList<>();
    List<FileBean> excelfiles = new ArrayList<>();

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_media_file;
    }

    @Override
    protected void loadData() {
        //扫描文件时间过长，缓存不为空，显示缓存
        List<File> files = MediaHelper.getInstance().getOfficeQueryCache();
        if (files != null) {
            onDataSuccess(files);
        } else {
            refreshLayout.autoRefresh();
        }
    }

    private void initAdapter(Context context) {
        wordfileAdapter = new FileAdapter(context, new ArrayList<>());
        wordfileAdapter.setOnFileBeanClickListener(new FileAdapter.OnFileBeanClickListener() {
            @Override
            public void onClick(FileBean fileBean, int pos) {
                selectFile(fileBean);
                wordfileAdapter.notifyItemChanged(pos);
            }
        });
        pdffileAdapter = new FileAdapter(context, new ArrayList<>());
        pdffileAdapter.setOnFileBeanClickListener(new FileAdapter.OnFileBeanClickListener() {
            @Override
            public void onClick(FileBean fileBean, int pos) {
                selectFile(fileBean);
                pdffileAdapter.notifyItemChanged(pos);
            }
        });
        pptfileAdapter = new FileAdapter(context, new ArrayList<>());
        pptfileAdapter.setOnFileBeanClickListener(new FileAdapter.OnFileBeanClickListener() {
            @Override
            public void onClick(FileBean fileBean, int pos) {
                selectFile(fileBean);
                pptfileAdapter.notifyItemChanged(pos);
            }
        });
        excelfileAdapter = new FileAdapter(context, new ArrayList<>());
        excelfileAdapter.setOnFileBeanClickListener(new FileAdapter.OnFileBeanClickListener() {
            @Override
            public void onClick(FileBean fileBean, int pos) {
                selectFile(fileBean);
                excelfileAdapter.notifyItemChanged(pos);
            }
        });
        ArrayList<FileBean> list = new ArrayList<>();
        FileBean fileBean = new FileBean();
        fileBean.setType(FileBean.DIR);
        fileBean.setTypeName("word");
        list.add(fileBean);
        wordAdapter = new TypeAdapter(context, list);
        wordAdapter.setOnTypeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileBean typeBean = wordAdapter.getData().get(0);
                if (typeBean.isExpand()) {
                    // 折叠
                    typeBean.setExpand(false);
                    expandMap.put(typeBean.getTypeName(), false);
                    wordfileAdapter.getData().clear();
                    wordfileAdapter.notifyItemRangeRemoved(0, wordFiles.size());
                } else {
                    //展开
                    typeBean.setExpand(true);
                    expandMap.put(typeBean.getTypeName(), true);
                    wordfileAdapter.getData().addAll(wordFiles);
                    wordfileAdapter.notifyItemRangeInserted(0, wordFiles.size());
                }
                wordAdapter.notifyItemChanged(0);
            }
        });

        ArrayList<FileBean> list2 = new ArrayList<>();
        FileBean fileBean2 = new FileBean();
        fileBean2.setType(FileBean.DIR);
        fileBean2.setTypeName("pdf");
        list2.add(fileBean2);
        pdfAdapter = new TypeAdapter(context, list2);
        pdfAdapter.setOnTypeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileBean typeBean = pdfAdapter.getData().get(0);
                if (typeBean.isExpand()) {
                    // 折叠
                    typeBean.setExpand(false);
                    expandMap.put(typeBean.getTypeName(), false);
                    pdffileAdapter.getData().clear();
                    pdffileAdapter.notifyItemRangeRemoved(0, pdffiles.size());
                } else {
                    //展开
                    typeBean.setExpand(true);
                    expandMap.put(typeBean.getTypeName(), true);
                    pdffileAdapter.getData().addAll(pdffiles);
                    pdffileAdapter.notifyItemRangeInserted(0, pdffiles.size());
                }
                pdfAdapter.notifyItemChanged(0);
            }
        });

        ArrayList<FileBean> list3 = new ArrayList<>();
        FileBean fileBean3 = new FileBean();
        fileBean3.setType(FileBean.DIR);
        fileBean3.setTypeName("ppt");
        list3.add(fileBean3);
        pptAdapter = new TypeAdapter(context, list3);
        pptAdapter.setOnTypeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileBean typeBean = pptAdapter.getData().get(0);
                if (typeBean.isExpand()) {
                    // 折叠
                    typeBean.setExpand(false);
                    expandMap.put(typeBean.getTypeName(), false);
                    pptfileAdapter.getData().clear();
                    pptfileAdapter.notifyItemRangeRemoved(0, pptfiles.size());
                } else {
                    //展开
                    typeBean.setExpand(true);
                    expandMap.put(typeBean.getTypeName(), true);
                    pptfileAdapter.getData().addAll(pptfiles);
                    pptfileAdapter.notifyItemRangeInserted(0, pptfiles.size());
                }
                pptAdapter.notifyItemChanged(0);
            }
        });

        ArrayList<FileBean> list4 = new ArrayList<>();
        FileBean fileBean4 = new FileBean();
        fileBean4.setType(FileBean.DIR);
        fileBean4.setTypeName("excel");
        list4.add(fileBean4);
        excelAdapter = new TypeAdapter(context, list4);
        excelAdapter.setOnTypeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileBean typeBean = excelAdapter.getData().get(0);
                if (typeBean.isExpand()) {
                    // 折叠
                    typeBean.setExpand(false);
                    expandMap.put(typeBean.getTypeName(), false);
                    excelfileAdapter.getData().clear();
                    excelfileAdapter.notifyItemRangeRemoved(0, excelfiles.size());
                } else {
                    //展开
                    typeBean.setExpand(true);
                    expandMap.put(typeBean.getTypeName(), true);
                    excelfileAdapter.getData().addAll(excelfiles);
                    excelfileAdapter.notifyItemRangeInserted(0, excelfiles.size());
                }
                excelAdapter.notifyItemChanged(0);
            }
        });

    }

    private void selectFile(FileBean fileBean) {
        if (AddMucFileActivity2.isAllowToSelect() || fileBean.isChecked()) {
            fileBean.setChecked(!fileBean.isChecked());
            //发送广播
            Intent intent = new Intent();
            intent.setAction(Action_Click);
            intent.putExtra(FileBean.FileBean_Key, fileBean);
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
        } else {
            Toast.makeText(mContext, mContext.getString(R.string.select_file_count_place_holder, 9), Toast.LENGTH_SHORT).show();
        }
        checkedMap.put(fileBean.getFile().getAbsolutePath(), fileBean.isChecked());
    }

    @Override
    protected void initView(View view) {
        refreshLayout = view.findViewById(R.id.refresh_layout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                realLoadData();
            }
        });

        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        delegateAdapter = new DelegateAdapter(layoutManager, false);
        recyclerView.setAdapter(delegateAdapter);

        initAdapter(mContext);
    }

    boolean once;//判断是否是首次进入，默认展开第一个列表

    private void onDataSuccess(List<File> files) {
        Observable.create(new ObservableOnSubscribe<Object>() {

            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                //耗时操作
                try {
                    if (!once) {
                        //设置第一项展开
                        once = true;
                        wordAdapter.getData().get(0).setExpand(true);
                        expandMap.put(wordAdapter.getData().get(0).getTypeName(), true);
                    }
                    fillData(files);
                    addAdapter();
                } catch (Exception e) {
                    emitter.onError(e);
                }
                emitter.onNext(new Object());
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {

                    @Override
                    public void accept(Object o) throws Exception {
                        refreshLayout.finishRefresh();
                        Log.e("lzs", "onSuccess");
                        delegateAdapter.clear();
                        delegateAdapter.setAdapters(adapterList);
                        delegateAdapter.notifyDataSetChanged();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
    }

    private void addAdapter() {
        adapterList.clear();
        if (wordFiles.size() > 0) {
            adapterList.add(wordAdapter);
            adapterList.add(wordfileAdapter);
            adapterList.add(new DividerAdapter(mContext));
        }
        if (pdffiles.size() > 0) {
            adapterList.add(pdfAdapter);
            adapterList.add(pdffileAdapter);
            adapterList.add(new DividerAdapter(mContext));
        }
        if (pptfiles.size() > 0) {
            adapterList.add(pptAdapter);
            adapterList.add(pptfileAdapter);
            adapterList.add(new DividerAdapter(mContext));
        }
        if (excelfiles.size() > 0) {
            adapterList.add(excelAdapter);
            adapterList.add(excelfileAdapter);
            adapterList.add(new DividerAdapter(mContext));
        }
        if (wordFiles.size() == 0 && pdffiles.size() == 0 && pptfiles.size() == 0 && excelfiles.size() == 0) {
            //无数据加载无数据页面
            adapterList.add(new EmptyAdapter(mContext));
        }
    }

    private void fillData(List<File> files) {
        for (int i = 0; i < files.size(); i++) {
            File file = files.get(i);
            String suffix = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".") + 1, file.getAbsolutePath().length());
            FileBean fileBean = new FileBean();
            fileBean.setFile(file);
            fileBean.setChecked(checkedMap.get(file.getAbsolutePath()) != null ? checkedMap.get(file.getAbsolutePath()) : false);
            fileBean.setFileName(file.getName());
            if ((suffix.equalsIgnoreCase("doc") || suffix.equalsIgnoreCase("docx")) && file.length() > 1024) {
                // 展开状态
                fileBean.setType(FileBean.DOC);
                if (expandMap.get(wordAdapter.getData().get(0).getTypeName()) != null && expandMap.get(wordAdapter.getData().get(0).getTypeName())) {
                    wordfileAdapter.getData().add(fileBean);
                }
                //折叠
                wordFiles.add(fileBean);
            } else if (suffix.equalsIgnoreCase("pdf") && file.length() > 1024) {
                // 展开状态
                fileBean.setType(FileBean.PDF);
                if (expandMap.get(pdfAdapter.getData().get(0).getTypeName()) != null && expandMap.get(pdfAdapter.getData().get(0).getTypeName())) {
                    pdffileAdapter.getData().add(fileBean);
                }
                //折叠
                pdffiles.add(fileBean);
            } else if ((suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx")) && file.length() > 1024) {
                fileBean.setType(FileBean.PPT);
                if (expandMap.get(pptAdapter.getData().get(0).getTypeName()) != null && expandMap.get(pptAdapter.getData().get(0).getTypeName())) {
                    // 展开状态
                    pptfileAdapter.getData().add(fileBean);
                }
                pptfiles.add(fileBean);
            } else if ((suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx")) && file.length() > 1024) {
                fileBean.setType(FileBean.EXCEL);
                if (expandMap.get(excelAdapter.getData().get(0).getTypeName()) != null && expandMap.get(excelAdapter.getData().get(0).getTypeName())) {
                    // 展开状态
                    excelfileAdapter.getData().add(fileBean);
                }
                excelfiles.add(fileBean);
            }
        }
    }

    private void realLoadData() {
        //查询
        MediaHelper.getInstance().getMediaOfficeDoc(getActivity().getContentResolver(), this);
    }


    @Override
    public void onSuccess(List<File> files) {
        refreshLayout.finishRefresh();
        onDataSuccess(files);
    }

    @Override
    public void onFailed(String msg) {
        refreshLayout.finishRefresh();
    }
}
